'use client'
import { ConfigProvider, Divider, theme} from "antd";
import zh_CN from 'antd/es/locale/zh_CN';
import TopBar from "@/app/components/home/topbar";
import React, {Suspense, useEffect, useState} from "react";
import {AuthorizedResources} from "@/app/lib/resource";
import Auth from "@/app/components/home/auth";
import {ResourceContext} from "@/app/lib/ResourceContext"
import {getFetch, postFetch} from "@/app/lib/HttpProtocol";
import {getCurrentWork} from "@/app/lib/security";
import Loading from "@/app/home/loading";
const apis:any ={
  workListApi: '/auth/work/list',
  authorizeApi: '/auth/authorize'
}

const topBarStyle:React.CSSProperties = {
  width:'100%',
  position:'fixed',
  zIndex:999,
  opacity:0.7,
  height:'10vh',
}

function decideWorkId(data:any) {
  if(data == null
    || data.length == 0){
    return undefined;
  }
  // @ts-ignore
  let work = data.find(d => d.primary == 1);
  if(work == undefined){
    work = data[0];
  }
  return work.id
}
async function loadResources(appname?:string){
  let work = getCurrentWork();
  if(work != null){
    return postFetch(apis.authorizeApi,{
      workId:work,
      appname:appname
    }).then(ress =>{
      return ress;
    })
  }
  return getFetch(apis.workListApi,null).then(data => {
    let workId = decideWorkId(data);
    return postFetch(apis.authorizeApi,{
      workId:workId,
      appname:appname
    }).then(ress =>{
      return ress;
    })
  })
}

export default function HomeLayout({
                                     children,
                                   }: Readonly<{
  children: React.ReactNode;
}>) {
  const [resources,setResources] = useState<AuthorizedResources>()
  useEffect(() => {
    loadResources(process.env.NEXT_PUBLIC_APPNAME).then(res => {
      // @ts-ignore
      setResources(res);
    });
  },[])
  return !resources ? <Loading /> : (
    <ConfigProvider theme={{algorithm:theme.defaultAlgorithm}} locale={zh_CN}>
      <Suspense>
      <ResourceContext.Provider value={resources}>
      <div style={topBarStyle} >
        <Auth/>
        <TopBar />
        <Divider orientationMargin={0} style={{margin:'0 0',opacity:'0.3'}}/>
      </div>
      {children}
      </ResourceContext.Provider>
    </Suspense>
    </ConfigProvider>
  );
}
